from flask import Blueprint, request, render_template, session
from toutiao.model.db_routing import Article, User, Channel, db

article_api = Blueprint('article', __name__, url_prefix='/article')

import json


@article_api.route('/add_article', methods=['POST'])
def add_article():
    """
    发表文章
    :return:
    """
    info = json.loads(request.data)

    user_id = info.get('user')
    channel_id = info.get('channel')
    title = info.get('title')

    user = User.query.filter_by(id=user_id).first()

    if not user:
        return {'code': 404, 'msg': '用户名不存在'}
    channel = Channel.query.filter_by(id=channel_id).first()
    if not channel:
        return {'code': 404, 'msg': '频道不存在'}
    if channel.is_visible == 1:
        return {'code': 404, 'msg': '此频道已删除，不能发布文章'}
    article = Article.query.filter_by(user_id=user_id, channel_id=channel_id, title=title).first()
    if article:

        return {'code': 200, 'msg': '文章已发布'}
    else:
        article_content = Article(user_id=user_id, channel_id=channel_id, title=title)
        user.article_count += 1
        db.session.add(article_content)
        db.session.commit()
        return {'code': 200, 'msg': '用户发布文章成功'}
